import { app } from "../lzbjpk_app";

const { ccclass } = cc._decorator;

@ccclass
export default class lzbjpk_ComTool extends cc.Component {

    public static Instance: lzbjpk_ComTool = null;
    JS_Name: string;
    protected onLoad(): void {
        if (lzbjpk_ComTool.Instance !== null) {
            this.destroy();
            return;
        }
        this.Init();
        lzbjpk_ComTool.Instance = this;
    }

    /**
 * 构造函数
 */
    Init() {
        this.JS_Name = app.subGameName + "_ComTool";
    }

    //---------------获取贴图路径----------------

    //获取数据对应的贴图资源
    GetImagePathByType(imageType: string, userData: Object):string {
        if (imageType == "HZShowCard") {
            return "texture/card/show/tiao2";
        }
        else if (imageType == "HZDownCard") {
            return "texture/card/down/tiao11";
        }
        else {
            console.error("GetImagePathByType(%s,%s) error", imageType, userData);
            return
        }
    }

    //获取转化后的玩家ID
    GetPid(pid: number): number {
        let serverID: number = Math.floor(pid / 100000000000);
        if (!serverID) {
            return pid
        }
        let playerID: number = pid - serverID * 100000000000;
        let temp = [serverID, playerID].join("");
        let res = Math.floor(parseInt(temp));
        return res;
    }

    //--------------引擎判断接口-------------
    //是否是安卓微信环境
    IsAndroidWeChatBrowser() {
        if (cc.sys.os != "Android") {
            return false
        }
        var browserType = cc.sys.browserType;

        //mqqbrowser 安卓中微信浏览器标示
        if (browserType == cc.sys.BROWSER_TYPE_MOBILE_QQ) {
            return true
        }
        //怕异常多处理wechat的判断 一般wechat是ios中微信标示
        else if (browserType == cc.sys.BROWSER_TYPE_WECHAT) {
            return true
        }

        return false
    }

    //是否是微信浏览器环境
    IsWeChatBrowser() {
        var browserType = cc.sys.browserType;

        //mqqbrowser 安卓中微信浏览器标示
        if (browserType == cc.sys.BROWSER_TYPE_MOBILE_QQ) {
            return true
        }
        //怕异常多处理wechat的判断 一般wechat是ios中微信标示
        else if (browserType == cc.sys.BROWSER_TYPE_WECHAT) {
            return true
        }

        return false
    }

    /**
     * 是否是ios平台
     * @returns {Boolean}
     */
    IsIOS() {
        var browserType = cc.sys.browserType;
        if (browserType) {
            return false
        }
        return cc.sys.os == cc.sys.OS_IOS
    }

    IsIpad() {
        var browserType = cc.sys.browserType;
        if (browserType) {
            return false
        }
        return cc.sys.isNative && cc.sys.platform == cc.sys.IPAD
    }

    //是否是安卓
    IsAndroid() {
        var browserType = cc.sys.browserType;
        if (browserType) {
            return false
        }
        return cc.sys.os == cc.sys.OS_ANDROID
    }

    //是否是win
    IsWindows() {
        var browserType = cc.sys.browserType;
        if (browserType) {
            return false
        }
        return cc.sys.os == cc.sys.OS_WINDOWS;
    }

    //----------------列表方法---------------
    //删除列表重复项
    DeleteListRepeat(arr: any[]): any[] {
        return Array.from(new Set(arr));
    }

    //第1个列表与第2个列表的交集
    TowListIntersect(arr1: any[], arr2: any[]): any[] {
        return arr1.filter(item => arr2.includes(item));
    }

    //第1个列表与第2个列表的差集
    TowListSubtraction(arr1: any[], arr2: any[]): any[] {
        return arr1.filter(item => !arr2.includes(item));
    }

    //2个列表的并集
    TowListUnion(arr1: any[], arr2: any[]): any[] {
        return arr1.concat(arr2.filter(item => !arr1.includes(item)));
    }

    //随机筛选列表指定个数出来
    ListSample(targetList: any[], choiceCount: number): any[] {
        var returnList = [];

        //需要拷贝一份避免原列表被修改
        var tempList = targetList.slice();
        var length = tempList.length;

        if (choiceCount > length) {
            throw new Error('Count cannot be greater than the length of the array');
        }

        const shuffled = tempList.slice().sort(() => Math.random() - 0.5);
        return shuffled.slice(0, choiceCount);
    }

    //列表随机1个出来
    ListChoice(arr: any[]): any {
        if (arr.length === 0) {
            throw new Error('Array cannot be empty');
        }

        const randomIndex = Math.floor(Math.random() * arr.length);
        return arr[randomIndex];
    }

    //求列表的最大值
    ListMaxNum(arr: number[]): number {
        if (arr.length === 0) {
            throw new Error('Array cannot be empty');
        }

        return Math.max(...arr);
    }

    //求列表的最小值
    ListMinNum(arr: number[]): number {
        if (arr.length === 0) {
            throw new Error('Array cannot be empty');
        }

        return Math.min(...arr);
    }

    //----------------字符串方法------------------
    //增加字符串数字后缀 ("btnFight", 1, 2)) - > "btnFight01"
    StringAddNumSuffix(targetString:string, num:number, suffixLen: number): string {
        var numString = "" + num;
        if (suffixLen) {
            var numLen = numString.length;
            numString = numLen < suffixLen ? (Array(suffixLen - numLen + 1).join('0') + num) : numString;
        }

        return [targetString, numString].join("");
    }

    //替换字符串中的文本("第{1}次", 10)) - > "第10次"
    StringReplace(str:string, index: number):string {
        return str.replace(new RegExp(`\\{${index}\\}`, 'g'), index.toString());
    }

    //去除左空格
    StringLeftTrim(str:string): string {
        return str.replace(/^\s+/, '');
    }
    //替换指定位置的字符串
    ReplacePosToStr(text:string, start: number, stop: number, replacetext:string) {
        let mystr = text.substring(0, stop - 1) + replacetext + text.substring(stop + 1);
        return mystr;
    }
    //去除右空格
    StringRightTrim(str:string) {
        return str.replace(/\s+$/, '');
    }
    //去除2边空格
    StringTrim(str:string) {
        return str.trim();
    }

    //---------------对象方法----------------
    //深拷贝(列表,字典)
    DeepCopy(target:any):any {
        return JSON.parse(JSON.stringify(target));
    }

    /**
     * 圆盘概率随机
     * @param curIDList
     * @param curRateList(必须是整数列表)
     * @param maxRate
     */
    GetDiskRandValue(curIDList, curRateList, maxRate) {
        //默认万分率随机
        if (!maxRate) {
            maxRate = 0;
            for (var index in curRateList) {
                var rate = curRateList[index];
                maxRate += rate;
            }
        }
        var listLength = curIDList.length
        if (!listLength) {
            console.error("GetDiskRandValue curIDList empty");
            return null
        }
        if (listLength != curRateList.length) {
            console.error("GetDiskRandValue (%s) != (%s)", curIDList, curRateList);
            return null
        }
        var oddsNum = this.RandInt(1, maxRate);

        var sortList = curRateList.map(function (rate, index) {
            var id = curIDList[index];
            return [rate, id];
        });
        //从小到大排序,相等按追加顺序排序
        sortList.sort(function (aList, bList) { return aList[0] > bList[0] ? 1 : -1 })

        var rateValue = 0;
        for (let index = 0; index < listLength; index++) {
            rateValue += sortList[index][0];
            if (rateValue < oddsNum) {
                continue;
            }
            return sortList[index][1];
        }

        console.error("curIDList:%s,%s,%s,%s not find value", curIDList, curRateList, oddsNum, sortList);

        return null;
    }
    /**
     * 获得一个随机整数 ：start<= randValue <= end
     * @param {Array} below
     * @return {Number}
     * @remarks {}
     */
    RandInt(start, end) {
        return Math.floor(Math.random() * (end + 1 - start) + start);
    }


    /**
     * 生成一个列表 range(0, 7)=>[0,1,2,3,4,5,6]
     */
    Range(...argList) {
        var start, end, step, len, returnList;
        returnList = [];
        len = argList.length;

        //一个参数
        if (len == 1) {
            start = 0;
            end = argList[0];
            step = 1;
        }
        else if (len == 2) {
            start = argList[0];
            end = argList[1];
            step = 1;
        }
        else {
            start = argList[0];
            end = argList[1];
            step = argList[2];
        }

        if (step < 0) {
            for (start; start > end; start += step) {
                returnList.push(start);
            }
        }
        else {
            for (start; start < end; start += step) {
                returnList.push(start);
            }

        }
        return returnList
    }

    /**
     * 获取字典数据格式字符串（支持字典嵌套）
     * @param {Object} curDict
     * @param {Number} tabNum
     * @return {String}
     */
    GetPrintDictStr(curDict, tabNum) {
        var key, value, classType, outEx, arg;

        tabNum = tabNum != null ? tabNum : 0;
        var outstr = "{\n";

        for (key in curDict) {
            value = curDict[key];
            classType = Object.prototype.toString.call(value).slice("[object ".length, -1);

            outEx = "";
            if (classType == "Object") {
                if (value.hasOwnProperty("JS_Name")) {
                    outEx = "(" + value.toString() + "),\n";
                }
                else {
                    outEx = this.GetPrintDictStr(value, tabNum + 1);
                }
            }
            else if (classType == "Function") {
                outEx = value.constructor.name + ",\n";
            }
            else {
                arg = "";
                try {
                    arg = JSON.stringify(value);
                }
                catch (e) {
                    //存在对象循环引用
                    arg = "### cyclic object value:" + value.toString();
                }
                outEx = arg + ",\n";
            }

            outstr += "\t" + this.GetTabStr(tabNum) + JSON.stringify(key) + ":" + outEx;
        }

        outstr += this.GetTabStr(tabNum) + "}";

        if (tabNum) {
            outstr += ",";
        }
        outstr += "\n";

        return outstr;
    }

    /**
     * 返回tab字符串个数
     * @param {Object} num
     * @return {String}
     */
    GetTabStr(num) {
        var outstr = "";
        while (num--) {
            outstr += "\t";
        }
        return outstr;
    }

    /**
     * 输出类属性信息
     * @param obj
     */
    OutPutClassProperty(obj) {
        var propertyDict = {};
        for (var property in obj) {
            propertyDict[property] = obj[property];
        }
    }



    /**
     *	获取时间天数差
     */
    GetDayDiffByTick(tick_1, tick_2) {
        var dateTime_1, dateTime_2;

        dateTime_1 = new Date(tick_1);
        dateTime_2 = new Date(tick_2);

        try {
            dateTime_1 = Date.parse((dateTime_1.getMonth() + 1) + "/" + dateTime_1.getDate() + "/" + dateTime_1.getFullYear());
            dateTime_2 = Date.parse((dateTime_2.getMonth() + 1) + "/" + dateTime_2.getDate() + "/" + dateTime_2.getFullYear());
            return Math.abs(dateTime_1 - dateTime_2) / (24 * 60 * 60 * 1000);
        }

        catch (e) {
            console.error("GetDayDiffByTick error(%s)", e.message);
        }
    }

    /**
     * 获取当前时间字符串格式: 2017/3/28 11:11
     */
    GetDateYearMonthDayHourMinuteString(time) {
        var date = new Date(time * 1000);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();

        return year + "/" + this.StringAddNumSuffix("", month, 2) + "/" + this.StringAddNumSuffix("", day, 2) + " " + this.StringAddNumSuffix("", hours, 2) + ":" + this.StringAddNumSuffix("", minutes, 2) + ":" + this.StringAddNumSuffix("", seconds, 2);
    }

    /**
     * 获取当前时间字符串格式
     * @returns {String} 2014-11-06
     */
    GetNowDateDayStr() {
        var myDate = new Date();

        var year = myDate.getFullYear();
        var month = myDate.getMonth() + 1;
        var day = myDate.getDate();
        return [this.StringAddNumSuffix("", year, 4), this.StringAddNumSuffix("", month, 2), this.StringAddNumSuffix("", day, 2)].join("-");
    }

    /**
	 * 获取当前时间字符串格式
	 * @returns {String} 2014-11
	 */
	GetNowDateMonthString(){
		var myDate = new Date();
		var year = myDate.getFullYear();
		var month = myDate.getMonth() + 1;
		return [this.StringAddNumSuffix("", year, 4), this.StringAddNumSuffix("", month, 2)].join("-");
	}

	/**
	 * 获取当前时间字符串格式
	 * @returns {String} 2014-11-06_193844
	 */
	GetNowDateTimeStr(){

		var myDate = new Date();

		var year = myDate.getFullYear();
		var month = myDate.getMonth() + 1;
		var day = myDate.getDate();
		var hour = myDate.getHours();
		var min = myDate.getMinutes();
		var second = myDate.getSeconds();

		var dateString = [this.StringAddNumSuffix("", year, 4), this.StringAddNumSuffix("", month, 2), this.StringAddNumSuffix("", day, 2)].join("-");
		dateString += "_";

		dateString += [this.StringAddNumSuffix("", hour, 2), this.StringAddNumSuffix("", min, 2), this.StringAddNumSuffix("", second, 2)].join(":");

		return dateString
	}

	formatSeconds (value:string) {
		var theTime: number = parseInt(value);// 秒
		var theTime1:number = 0;// 分
		var theTime2:number = 0;// 小时

		if (theTime > 60) {
			theTime1 = parseInt((theTime / 60).toString());
			theTime = parseInt((theTime % 60).toString());

			if (theTime1 > 60) {
				theTime2 = parseInt((theTime1 / 60).toString());
				theTime1 = parseInt((theTime1 % 60).toString());
			}
		}

		var result = "" + parseInt(theTime.toString());
		if (theTime1 > 0) {
			result = "" + parseInt(theTime1.toString()) + ":" + result;
		} else {
			result = "" + "00" + ":" + result;
		}
		if (theTime2 > 0) {
			result = "" + parseInt(theTime2.toString()) + ":" + result;
		} else {
			result = "" + "00" + ":" + result;
		}
		return result;
	}
}
